<template>
  <div class="divBox">
    <el-card class="box-card">
      <div class="clearfix">
        <!-- <el-steps :active="currentTab" align-center finish-status="success">
          <el-step title="服务信息" />
          <el-step title="服务详情" />
        </el-steps> -->
        <el-tabs v-if="headTab.length > 0" v-model="currentTab">
          <el-tab-pane
            v-for="(item, index) in headTab"
            :key="index"
            :name="item.name"
            :label="item.title"
          />
        </el-tabs>
      </div>
      <el-form
        ref="formValidate"
        :key="currentTab"
        v-loading="fullscreenLoading"
        class="formValidate mt20"
        :rules="ruleValidate"
        :model="formValidate"
        label-width="130px"
        @submit.native.prevent
      >
        <el-row v-if="currentTab == '1'" :gutter="24">
          <!-- 服务信息-->
          <el-col :span="24">
            <el-form-item label="服务名称：" prop="name">
              <el-input
                v-model="formValidate.name"
                placeholder="请输入服务名称"
                class="selWidth"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务分类：" prop="category_id">
              <el-select v-model="formValidate.category_id" placeholder="请选择" class="filter-item selWidth" clearable
                         @change="getList(1)">
                <el-option v-for="item in categoryList.list" :key="item.industry_id" :label="item.industry_name"
                           :value="item.industry_id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务封面图：" prop="image">
              <div
                class="upLoadPicBox"
                title="750*750px"
                @click="modalPicTap('1')"
              >
                <div v-if="formValidate.image" class="pictrue">
                  <img :src="formValidate.image">
                </div>
                <div v-else class="upLoad">
                  <i class="el-icon-camera cameraIconfont" />
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务轮播图：" prop="slider_image">
              <div class="acea-row">
                <div
                  v-for="(item, index) in formValidate.slider_image"
                  :key="index"
                  class="pictrue"
                  draggable="false"
                  @dragstart="handleDragStart($event, item)"
                  @dragover.prevent="handleDragOver($event, item)"
                  @dragenter="handleDragEnter($event, item)"
                  @dragend="handleDragEnd($event, item)"
                >
                  <img :src="item">
                  <i
                    class="el-icon-error btndel"
                    @click="handleRemove(index)"
                  />
                </div>
                <div
                  v-if="formValidate.slider_image.length < 10"
                  class="uploadCont"
                  title="750*750px"
                >
                  <div class="upLoadPicBox" @click="modalPicTap('2')">
                    <div class="upLoad">
                      <i class="el-icon-camera cameraIconfont" />
                    </div>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务者：" prop="service_staff_id">
              <el-select
                ref="serviceStaffSelect"
                v-model="formValidate.service_staff"
                :remote-method="querySearch"
                filterable
                default-first-option
                remote
                placeholder="选择服务者"
                class="header-search-select selWidth"
                multiple
                value-key="id"
                remote-show-suffix
              >
                <template v-for="item in serviceOptions">
                  <el-option  :key="item.id" :value="item" :label="item.name" />
                </template>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col>
            <el-form-item label="推荐到首页：">
              <el-switch
                v-model="formValidate.is_home"
                :active-value="1"
                :inactive-value="0"
                active-text="开启"
                inactive-text="关闭"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="服务简介：" prop="store_info">
              <el-input
                v-model="formValidate.info"
                type="textarea"
                :rows="3"
                placeholder="请输入服务简介"
                class="selWidth"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="售价：">
              <el-input-number
                :controls="false"
                v-model="formValidate.price"
                :min="0"
                :precision="2"
                :max="9999999999"
                class="content_width"
                :active-change="false"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="原价：">
              <el-input-number
                :controls="false"
                v-model="formValidate.old_price"
                :min="0"
                :max="9999999999"
                :precision="2"
                :active-change="false"
                class="content_width"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序：">
              <el-input-number
                :controls="false"
                v-model="formValidate.sort"
                :min="0"
                :max="9999999999"
                :precision="0"
                :active-change="false"
                class="content_width"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 服务详情-->
        <el-row v-if="currentTab == '2'">
          <el-col :span="24">
            <el-form-item label="服务详情：">
              <vue-ueditor-wrap
                v-model="formValidate.content"
                :config="myConfig"
                @beforeInit="addCustomDialog"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="margin-top:30px;">
          <el-button
            v-show="currentTab > 1"
            type="primary"
            class="submission"
            size="small"
            @click="handleSubmitUp"
          >上一步
          </el-button>
          <el-button
            v-show="currentTab < 5"
            type="primary"
            class="submission"
            size="small"
            @click="handleSubmitNest('formValidate')"
          >下一步
          </el-button>
          <el-button
            v-show="currentTab == '2' || $route.params.id"
            :loading="loading"
            type="primary"
            class="submission"
            size="small"
            @click="handleSubmit('formValidate')"
          >提交
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

  </div>
</template>

<script>
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
import ueditorFrom from '@/components/ueditorFrom'
import VueUeditorWrap from 'vue-ueditor-wrap'
import {
  serviceCreateApi,
  serviceDetailApi,
  serviceUpdateApi,
  serviceStaffListApi ,
  categoryListApi
} from '@/api/reservationService'
import { roterPre } from '@/settings'
import SettingMer from '@/libs/settingMer'
import { getToken } from '@/utils/auth'

const defaultObj = {
  image: '',
  slider_image: [],
  name: '',
  category_id: '', // 服务分类id
  sort: 0,
  content: '',
  price: 0,
  old_price: 0,
  is_home: 0,
  service_staff: [],
}
export default {
  name: 'ServiceAdd',
  components: {
    ueditorFrom,
    VueUeditorWrap
  },
  data() {
    const url =
      SettingMer.https + '/upload/image/0/file?ueditor=1&token=' + getToken()
    return {
      isxfk : 0,
      myConfig: {
        autoHeightEnabled: false, // 编辑器不自动被内容撑高
        initialFrameHeight: 500, // 初始容器高度
        initialFrameWidth: '100%', // 初始容器
        enableAutoSave: false,
        UEDITOR_HOME_URL: '/UEditor/',
        serverUrl: url,
        imageUrl: url,
        imageFieldName: 'file',
        imageUrlPrefix: '',
        imageActionName: 'upfile',
        imageMaxSize: 2048000,
        imageAllowFiles: ['.png', '.jpg', '.jpeg', '.gif', '.bmp']
      },
      optionsCate: {
        value: 'store_category_id',
        label: 'cate_name',
        children: 'children',
        emitPath: false
      },
      serviceOptions: [],
      roterPre: roterPre,
      selectRule: '',
      checkboxGroup: [],
      tabs: [],
      fullscreenLoading: false,
      props: { emitPath: false },
      propsMer: { emitPath: true },
      active: 0,
      deduction_set: -1,
      ruleList: [],
      categoryList: [], // 服务分类筛选
      formValidate: Object.assign({}, defaultObj),
      picValidate: true,
      formDynamics: {
        template_name: '',
        template_value: []
      },
      manyTabTit: {},
      manyTabDate: {},
      grid2: {
        xl: 10,
        lg: 12,
        md: 12,
        sm: 24,
        xs: 24
      },
      isBtn: false,
      images: [],
      currentTab: '1',
      isChoice: '',
      upload: {
        videoIng: false // 是否显示进度条；
      },
      progress: 10, // 进度条默认0
      videoLink: '',
      grid: {
        xl: 8,
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24
      },
      loading: false,
      ruleValidate: {
        name: [
          { required: true, message: '请输入服务名称', trigger: 'blur' }
        ],
        category_id: [
          { required: true, message: '请选择服务分类', trigger: 'change' }
        ],
        info: [
          { required: true, message: '请输入服务简介', trigger: 'blur' }
        ],
        image: [{ required: true, message: '请上传服务图', trigger: 'change' }],
        slider_image: [
          {
            required: true,
            message: '请上传服务轮播图',
            type: 'array',
            trigger: 'change'
          }
        ]
      },
      headTab: [
        { title: '服务信息', name: '1' },
        { title: '服务详情', name: '2' }
      ],
      type: 0,
      modals: false,
      createService: false,
      createCount: this.$route.params.id ? 0 : -10,
      virtualList:[],
      tabIndex: 0,
			tabName: "",
      search: '',
    }
  },
  computed: {
    attrValue() {
      const obj = Object.assign({}, this.attrVal)
      return obj
    },
    // oneFormBatch() {
    //   const obj = [Object.assign({}, defaultObj.attrValue[0])]
    //   if (this.OneattrValue[0] && this.OneattrValue[0]['image']) { obj[0]['image'] = this.OneattrValue[0]['image'] }
    //   obj[0]['attr'] = '全部'
    //   delete obj[0].bar_code
    //   return obj
    // }
  },
  watch: {
  },
  created() {
    this.tempRoute = Object.assign({}, this.$route)
  },
  mounted() {
    this.formValidate.slider_image = []
    this.querySearch()
    if (this.$route.params.id) {
      this.setTagsViewTitle()
      this.getInfo()
    }
    this.getCategoryList()
    this.$store.dispatch('settings/setEdit', true)
  },
  destroyed() {
    window.removeEventListener('popstate', this.goBack, false)
  },
  methods: {
    setTagsViewTitle() {
      const title = '编辑服务'
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}-${this.$route.params.id}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    elChangeExForArray(index1, index2, array) {
      const temp = array[index1]
      array[index1] = array[index2]
      array[index2] = temp
      return array
    },
    goBack() {
      sessionStorage.clear()
      window.history.back()
    },

    doCombination(arr) {
      var count = arr.length - 1; //数组长度(从0开始)
      var tmp = [];
      var totalArr = [];// 总数组
      return doCombinationCallback(arr, 0);//从第一个开始
      //js 没有静态数据，为了避免和外部数据混淆，需要使用闭包的形式
      function doCombinationCallback(arr, curr_index) {
        for(let val of arr[curr_index]) {
          tmp[curr_index] = val;//以curr_index为索引，加入数组
          //当前循环下标小于数组总长度，则需要继续调用方法
          if(curr_index < count) {
            doCombinationCallback(arr, curr_index + 1);//继续调用
          }else{
            totalArr.push(tmp.join(','));//(直接给push进去，push进去的不是值，而是值的地址)
          }
          //js  对象都是 地址引用(引用关系)，每次都需要重新初始化，否则 totalArr的数据都会是最后一次的 tmp 数据；
          let oldTmp = tmp;
          tmp = [];
          for(let index of oldTmp) {
            tmp.push(index);
          }
        }
        return totalArr;
      }
    },
    watCh(val) {
      const tmp = {}
      const tmpTab = {}
      this.formValidate.attr.forEach((o, i) => {
        tmp['value' + i] = { title: o.value }
        tmpTab['value' + i] = ''
      })
      if(this.isGenerate || this.createCount == 1){
        this.ManyAttrValue = this.attrFormat(val)
        this.manyTabTit = tmp
        this.manyTabDate = tmpTab
        this.formThead = Object.assign({}, this.formThead, tmp)
      }
      this.isGenerate = false
      this.addGenerate = false
    },
    // 服务分类；
    getCategoryList() {
      categoryListApi()
        .then(res => {
          this.categoryList = res.data
        })
        .catch(res => {
          this.$message.error(res.message)
        })
    },
    // 乘法
    accMul(arg1, arg2) {
      var max = 0
      var s1 = arg1.toString()
      var s2 = arg2.toString()
      try {
        max += s1.split('.')[1].length
      } catch (e) {}
      try {
        max += s2.split('.')[1].length
      } catch (e) {}
      return (
        (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) /
        Math.pow(10, max)
      )
    },
    // 添加按钮
    addBtn() {
      this.clearAttr()
      this.isBtn = true
      this.addGenerate = true
    },
    // 详情
    getInfo() {
      this.fullscreenLoading = true;
      serviceDetailApi(this.$route.params.id)
        .then(async res => {
          let info = res.data;
          this.infoData(info);
        })
        .catch(res => {
          this.fullscreenLoading = false;
          this.$message.error(res.message);
        });
    },
    infoData(info) {
      this.formValidate = {
        image: info.image,
        slider_image: info.slider_image,
        name: info.name,
        info: info.info,
        category_id: info.category_id, // 服务分类id
        sort: info.sort,
        content: info.content,
        price: info.price,
        old_price: info.old_price,
        is_home: info.is_home,
        service_staff: info.service_staff,
      };
      this.fullscreenLoading = false;
    },
    handleRemove(i) {
      this.formValidate.slider_image.splice(i, 1);
    },
    handleSubmitUp() {
      this.currentTab = (Number(this.currentTab) - 1).toString();
    },
    handleSubmitNest(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.currentTab = (Number(this.currentTab) + 1).toString();
        }
      });
    },
    // 提交
    handleSubmit(name) {
      this.$store.dispatch("settings/setEdit", false);
      this.$refs[name].validate(valid => {
        if (valid) {
          this.fullscreenLoading = true;
          this.loading = true;
          let disCreate = this.$route.params.id && !this.$route.query.type;
          if(this.isxfk == 1){
            disCreate = false
          }
          disCreate
            ? serviceUpdateApi(this.$route.params.id, this.formValidate)
                .then(async res => {
                  this.fullscreenLoading = false;
                  this.$message.success(res.message);
                  this.$router.push({ path: this.roterPre + "/reservation/service" });
                  this.$refs[name].resetFields();
                  this.formValidate.slider_image = [];
                  this.loading = false;
                })
                .catch(res => {
                  this.fullscreenLoading = false;
                  this.loading = false;
                  this.$message.error(res.message);
                })
            : serviceCreateApi(this.formValidate)
                .then(async res => {
                  this.fullscreenLoading = false;
                  this.$message.success(res.message);
                  this.$router.push({ path: this.roterPre + "/reservation/service" });
                  this.loading = false;
                })
                .catch(res => {
                  this.fullscreenLoading = false;
                  this.loading = false;
                  this.$message.error(res.message);
                });
        } else {
          if (!this.formValidate.name.trim()) {
            return this.$message.warning("基本信息-服务名称不能为空");
          }
          if (!this.formValidate.category_id) {
            return this.$message.warning("基本信息-服务分类不能为空");
          }
          // if (!this.formValidate.mer_cate_id) {
          //   return this.$message.warning("基本信息-门店服务分类不能为空");
          // }
          if (!this.formValidate.image) {
            return this.$message.warning("基本信息-服务封面图不能为空");
          }
          if (this.formValidate.slider_image.length < 0) {
            return this.$message.warning("基本信息-服务轮播图不能为空");
          }
        }
      });
    },
    // 点击商品图
    modalPicTap(tit, num, i) {
      const _this = this;
      const attr = [];
      this.$modalUpload(function(img) {
        if (tit === "1" && !num) {
          _this.formValidate.image = img[0];
        }
        if (tit === "2" && !num) {
          img.map(item => {
            attr.push(item.attachment_src);
            _this.formValidate.slider_image.push(item);
            if (_this.formValidate.slider_image.length > 10) {
              _this.formValidate.slider_image.length = 10;
            }
          });
        }
      }, tit);
    },
    // 表单验证
    validate(prop, status, error) {
      if (status === false) {
        this.$message.warning(error);
      }
    },
    // 规格图片验证
    specPicValidate(ManyAttrValue) {
      for (let i = 0; i < ManyAttrValue.length; i++) {
        if (ManyAttrValue[i].image === "" || !ManyAttrValue[i].image) {
          this.$message.warning("请上传服务规格图！");
          this.picValidate = false;
          break;
        }
      }
    },
    // 移动
    handleDragStart(e, item) {
      this.dragging = item;
    },
    handleDragEnd(e, item) {
      this.dragging = null;
    },
    handleDragOver(e) {
      e.dataTransfer.dropEffect = "move";
    },
    handleDragEnter(e, item) {
      e.dataTransfer.effectAllowed = "move";
      if (item === this.dragging) {
        return;
      }
      const newItems = [...this.formValidate.slider_image];
      const src = newItems.indexOf(this.dragging);
      const dst = newItems.indexOf(item);
      newItems.splice(dst, 0, ...newItems.splice(src, 1));
      this.formValidate.slider_image = newItems;
    },
    querySearch(query) {
       serviceStaffListApi()
        .then(async res => {
          this.serviceOptions = res.data.list.map(item => {return {id: item.staff_id, name: item.name};})
        })
        .catch(res => {
          this.$message.error(res.message);
        });
    },
    // 添加自定义弹窗
    addCustomDialog(editorId) {
      window.UE.registerUI(
        "test-dialog",
        function(editor, uiName) {
          // 创建 dialog
          let dialog = new window.UE.ui.Dialog({
            iframeUrl: roterPre + "/admin/widget/image?field=dialog",
            editor: editor,
            name: uiName,
            title: "上传图片",
            cssRules: "width:1200px;height:500px;padding:20px;"
          });
          this.dialog = dialog;
          let btn = new window.UE.ui.Button({
            name: "dialog-button",
            title: "上传图片",
            cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -726px -77px;`,
            onclick: function() {
              // 渲染dialog
              dialog.render();
              dialog.open();
            }
          });
          return btn;
        },
        37
      );
      window.UE.registerUI(
        "video-dialog",
        function(editor, uiName) {
          let dialog = new window.UE.ui.Dialog({
            iframeUrl: roterPre + "/admin/widget/video?fodder=video",
            editor: editor,
            name: uiName,
            title: "上传视频",
            cssRules: "width:600px;height:420px;padding:10px 20px 20px;"
          });
          this.dialog = dialog;
          let btn = new window.UE.ui.Button({
            name: "video-button",
            title: "上传视频",
            cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -320px -20px;`,
            onclick: function() {
              // 渲染dialog
              dialog.render();
              dialog.open();
            }
          });
          return btn;
        },
        38
      );
    }
  }
};
</script>
<style scoped lang="scss">
.bg {
  z-index: 100;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}
.goods_detail .goods_detail_wrapper {
  z-index: -10;
}
/deep/ .upLoadPicBox {
  .upLoad {
    -webkit-box-orient: vertical;
    -moz-box-orient: vertical;
    -o-box-orient: vertical;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
    line-height: 20px;
  }
  span {
    font-size: 10px;
  }
}
.proCoupon {
  /deep/ .el-form-item__content {
    margin-top: 5px;
  }
}
.tabPic {
  width: 40px !important;
  height: 40px !important;
  img {
    width: 100%;
    height: 100%;
  }
}
.noLeft {
  /deep/ .el-form-item__content {
    margin-left: 0 !important;
  }
}
.tabNumWidth {
  /deep/ .el-input-number--medium {
    width: 100px;
  }
  /deep/ .el-input-number__increase {
    width: 20px !important;
    font-size: 12px !important;
  }
  /deep/ .el-input-number__decrease {
    width: 20px !important;
    font-size: 12px !important;
  }
  /deep/ .el-input-number--medium .el-input__inner {
    padding-left: 25px !important;
    padding-right: 25px !important;
  }
  /deep/.priceBox .el-input-number__decrease,
  /deep/.priceBox .el-input-number__increase {
    display: none;
  }
  /deep/.priceBox .el-input-number.is-controls-right .el-input__inner {
    padding: 0 5px;
  }
  /deep/ thead {
    line-height: normal !important;
  }
  /deep/.cell {
    line-height: normal !important;
    text-overflow: clip !important;
  }
}
.seeCatMy {
  color: #2d8cf0;
  cursor: pointer;
}
.selectOn{
	color: #2d8cf0;
}
.virtual_boder {
  border: 1px solid #1890ff;
}
.virtual_boder2 {
  border: 1px solid #e7e7e7;
}
.virtual_san {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 0;
  height: 0;
  border-bottom: 26px solid #1890ff;
  border-left: 26px solid transparent;
}
.virtual_dui {
  position: absolute;
  bottom: -2px;
  right: 2px;
  color: #ffffff;
  font-family: system-ui;
}
.virtual {
  width: 120px;
  height: 60px;
  background: #ffffff;
  border-radius: 3px;
  float: left;
  text-align: center;
  padding-top: 8px;
  position: relative;
  cursor: pointer;
  line-height: 23px;
  .virtual_top {
    font-size: 14px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.85);
  }
  .virtual_bottom {
    font-size: 12px;
    font-weight: 400;
    color: #999999;
  }
}
.virtual:nth-child(2n) {
  margin: 0 12px;
}
.addfont {
  display: inline-block;
  font-size: 13px;
  font-weight: 400;
  color: #1890ff;
  margin-left: 14px;
  cursor: pointer;
}
.titTip {
  display: inline-bolck;
  font-size: 12px;
  font-weight: 400;
  color: #999999;
}
.addCustom_content {
  margin-top: 20px;
  .custom_box {
    margin-bottom: 10px;
  }
}
.addCustomBox {
  margin-top: 12px;
  font-size: 13px;
  font-weight: 400;
  color: #1890ff;
  .btn {
    cursor: pointer;
    width: max-content;
  }
  .remark {
    display: flex;
    margin-top: 14px;
  }
}
.selWidth {
  width: 50%;
}
.ml15 {
  margin-left: 15px;
}
.button-new-tag {
  height: 28px;
  line-height: 26px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 10px;
  position: relative;
  cursor: pointer;
  img {
    width: 100%;
    height: 100%;
  }
}
.iview-video-style {
  width: 40%;
  height: 180px;
  border-radius: 10px;
  background-color: #707070;
  margin-top: 10px;
  position: relative;
  overflow: hidden;
}
.iconv {
  color: #fff;
  line-height: 180px;
  display: inherit;
  font-size: 26px;
  position: absolute;
  top: -74px;
  left: 50%;
  margin-left: -25px;
}
.iview-video-style .mark {
  position: absolute;
  width: 100%;
  height: 30px;
  top: 0;
  background-color: rgba(0, 0, 0, 0.5);
  text-align: center;
}
.uploadVideo {
  margin-left: 10px;
}
.perW50 {
  width: 50%;
}
.submission {
  margin-left: 10px;
}
.btndel {
  position: absolute;
  z-index: 1;
  width: 20px !important;
  height: 20px !important;
  left: 46px;
  top: -4px;
}
.labeltop {
  /deep/ .el-form-item__label {
    float: none !important;
    display: inline-block !important;
    margin-left: 120px !important;
    width: auto !important;
  }
}
</style>
